<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


/**
 * 意见反馈。用户留言
 */
class Feedback extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'feedback';



    /**
     * 获取未回复留言个数
     */
    public function getUncheckeFeedbackNumber()
    {
        return $this->whereNull('manage_feedback')->count();
    }


    /**
     * 用户留言
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param type  0 或空，表示全部   1 已回复  2 未回复
     * @param start_time   开始时间
     * @param end_time   开始时间
     * @param keywords  筛选内容
     */
    public function lists($type, $keywords, $start_time, $end_time, $limit)
    {
        $res = $this->where(function ($query) use ($type, $start_time, $end_time) {
            if ($type == 1) {
                $query->whereNotNull('manage_feedback');
            } elseif ($type == 2) {
                $query->whereNull('manage_feedback');
            }

            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })->where(function ($query) use ($keywords) {
            if ($keywords) {
                $query->where('username', 'like', "%$keywords%")
                    ->orWhere('tel', 'like', "%$keywords%")
                    ->orWhere('feedback', 'like', "%$keywords%");
            }
        })->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();
        $userInfoObj = new UserInfo();
        $userLibraryInfoObj = new UserLibraryInfo();
        foreach ($res['data'] as $key => $val) {
            if ($val['user_id']) {
                $account_id = $userInfoObj->getAccountId($val['user_id']);
                $res['data'][$key]['account'] = $account_id ? $userLibraryInfoObj->getAccountByAccountId($account_id) : '';
            }
            $res['data'][$key]['img'] = $val['img'] ? explode("|", $val['img']) : [];
        }
        return $res;
    }

    /**
     * 回复用户留言（只能回复一次）
     * @param id 留言id
     * @param content 回复内容
     */
    public function reply($id, $content)
    {
        $res = $this->find($id);
        if (empty($res) || !empty($res['manage_feedback'])) {
            throw new Exception('参数错误');
        }
        $res->manage_feedback = $content;
        $res->manage_id = request()->manage_id;
        $res->save();
        return $res;
    }
}
